# script to make and print ECA maps
# requires arcpy and python 2.7
# uses *.mxd file as template that needs to contain the background layers (Land, ECA boundaries)
# this will need to be updated accordingly to find appropriate files

try:
    import archook #The module which locates arcgis
    archook.get_arcpy()
    import arcpy
except ImportError:
    error
    # do whatever you do if arcpy isnt there.
    
import os

## map templates
map_temp = r"H:\My Drive\Boats\ReplicationCode\analysis_code\mapping\eca_template_routes_v2.mxd"
track_temp = r"H:\My Drive\Boats\ReplicationCode\analysis_code\mapping\tracks_template.lyr"

## location of voyage shape file
track_file = r"H:\My Drive\Boats\ReplicationCode\data\final\voyages_shp\voyages.shp" 

## output folder
mapsout_dir = r"H:\My Drive\Boats\ReplicationCode\results\maps"

# output resolution
res = 300 

# tracks to remove
tracks_cond = r'( ("inter_port"=0) and ("km_onland"<5) ) ' 

# list of route and vessel combinations to map
vessel_routes_list = [  ('container','sf_la')     , ('othercargo','sf_la')      , ('tanker','sf_la') , 
                        ('container','lalb_exit') , ('othercargo','lalb_exit') , ('tanker','lalb_exit'),
                        ('container','sf_exit') , ('othercargo','sf_exit') , ('tanker','sf_exit')]

                        #('container','la_seattle') , ('othercargo','la_seattle') , ('tanker','la_seattle') ,
                        #('container','sf_seattle') , ('othercargo','sf_seattle') , ('tanker','sf_seattle')
   
# policy periods to map   
track_file_tags = ["preECA" ,"CA_ECA2009","CA_ECA2011"] # ,"CANA01"

# make folder for output
if not os.path.exists(mapsout_dir):
    os.makedirs(mapsout_dir)   

# get map template
mxd = arcpy.mapping.MapDocument(map_temp)

# get track layer template
symLayer = arcpy.mapping.Layer(track_temp)

# get data frame
df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]

# get ports layer and ECA layers
ports_lyr = arcpy.mapping.ListLayers(mxd, "west_coast_ports_eca100", df)[0]
study_area_lyr = arcpy.mapping.ListLayers(mxd, "StudyAreaBounds", df)[0]
CAECA09_lyr = arcpy.mapping.ListLayers(mxd, "CAeca_200907", df)[0]
CAECA11_lyr = arcpy.mapping.ListLayers(mxd, "CAeca_201112", df)[0]
NAECA_lyr = arcpy.mapping.ListLayers(mxd, "eca_boundary", df)[0]
display_lyr = arcpy.mapping.ListLayers(mxd, "port_display_buffer_v2", df)[0]

try:

    #### PLOTTING TRACKS ##############################
    # loop through options list and plot
    for vr in vessel_routes_list :

        vesselInclude = vr[0] 
        routesInclude = vr[1]   
                
        if vesselInclude=='container' :
            toInclude = r"""( "group_agg"='FCC' )  """
        elif vesselInclude=='tanker' :
            toInclude = r"""( "group_agg"='Tankers' )  """
        elif vesselInclude=='othercargo' :
            toInclude = r"""("group_agg"='Bulker' or "group_agg"='Other Cargo')  """
        
        # setting conditions for routes to select and ports to zoom to
        if routesInclude=='sf_la' :
            #route_select = '( ( (Port1=3 or Port1=4) and Port2=1 ) or ( (Port2=3 or Port2=4) and Port1=1 ) )'
            route_select = r"""( "route_name"='LALB_SFBay' )"""
            arcpy.SelectLayerByAttribute_management(ports_lyr, "NEW_SELECTION", "PORT_ID = 1 OR PORT_ID = 3")
            arcpy.SelectLayerByAttribute_management(display_lyr, "ADD_TO_SELECTION", "OBJECTID = 8") # this is to extend map west a bit

        elif routesInclude=='la_seattle' :
            route_select = r"""( "route_name"='LALB_Sea' )"""
            arcpy.SelectLayerByAttribute_management(ports_lyr, "NEW_SELECTION", "PORT_ID = 3 OR PORT_ID = 7")
            arcpy.SelectLayerByAttribute_management(display_lyr, "ADD_TO_SELECTION", "OBJECTID = 5") # this is to extend map west a bit

        elif routesInclude=='sf_seattle' :
            route_select = r"""( "route_name"='SFBay_Sea' )"""
            arcpy.SelectLayerByAttribute_management(ports_lyr, "NEW_SELECTION", "PORT_ID = 1 OR PORT_ID = 7")
            arcpy.SelectLayerByAttribute_management(display_lyr, "ADD_TO_SELECTION", "OBJECTID = 5") # this is to extend map west a bit

        elif routesInclude=='sf_port':
            route_select = r"""( "route_name"='SFBay_Port' )"""
            arcpy.SelectLayerByAttribute_management(ports_lyr, "NEW_SELECTION", "PORT_ID = 1 OR PORT_ID = 6")
            arcpy.SelectLayerByAttribute_management(display_lyr, "ADD_TO_SELECTION", "OBJECTID = 5") # this is to extend map west a bit

        elif  routesInclude=='la_port':
            route_select = r"""( "route_name"='LALB_Port' )"""
            arcpy.SelectLayerByAttribute_management(ports_lyr, "NEW_SELECTION", "PORT_ID = 3 OR PORT_ID = 6")
            arcpy.SelectLayerByAttribute_management(display_lyr, "ADD_TO_SELECTION", "OBJECTID = 5") # this is to extend map west a bit

        elif routesInclude=='seattle_port':
            route_select = r"""( "route_name"='Port_Sea' )"""
            arcpy.SelectLayerByAttribute_management(ports_lyr, "NEW_SELECTION", "PORT_ID = 6 OR PORT_ID = 7")
            arcpy.SelectLayerByAttribute_management(display_lyr, "ADD_TO_SELECTION", "OBJECTID = 9") # this is to extend map west a bit
            
        elif routesInclude=='seattle_south' :
            route_select = ' ( ("PORT1"=7 and "PORT2" in (101,102,103)) or ("PORT2"=7 and "PORT1" in (101,102,103)) ) '
            arcpy.SelectLayerByAttribute_management(ports_lyr, "NEW_SELECTION", "PORT_ID = 101 OR PORT_ID = 7")
            arcpy.SelectLayerByAttribute_management(display_lyr, "ADD_TO_SELECTION", "OBJECTID = 5") # this is to extend map west a bit
            
        elif routesInclude=='sea_port_exit' :
            route_select = ' ( ("PORT1" in (6,7) and "PORT2">100 ) or ("PORT2" in (6,7) and "PORT2">100 ) ) '
            arcpy.SelectLayerByAttribute_management(ports_lyr, "NEW_SELECTION", "PORT_ID = 7 OR PORT_ID = 103")
            arcpy.SelectLayerByAttribute_management(display_lyr, "ADD_TO_SELECTION", "OBJECTID = 5") # this is to extend map west a bit  
            
        elif routesInclude=='sea_port_all' :
            # seattle and portland port-to-port
            route_select = ' ( ("PORT1" in (6,7) and "PORT2"<=13 and not "PORT2" in (0,1,2,3,4,5,12) ) or ("PORT2" in (6,7) and "PORT1"<=13 and not "PORT1" in (0,1,2,3,4,5,12) )  and (INTERP_FLA=0) ) '
            arcpy.SelectLayerByAttribute_management(ports_lyr, "NEW_SELECTION", "PORT_ID = 7 OR PORT_ID = 103")
            arcpy.SelectLayerByAttribute_management(display_lyr, "ADD_TO_SELECTION", "OBJECTID = 5") # this is to extend map west a bit 
            
        elif routesInclude=='sea_port_long' :
            # seattle and portland port-to-port
            route_select = ' ( ("PORT1" in (6,7) and  "PORT2">13 and "PORT2"<50 and not "PORT2" in (0,1,2,3,4,5,12) ) or ("PORT2" in (6,7) and  "PORT1">13 and "PORT1"<50 and not "PORT1" in (0,1,2,3,4,5,12) ) ) '
            arcpy.SelectLayerByAttribute_management(ports_lyr, "NEW_SELECTION", "PORT_ID = 7 OR PORT_ID = 103")
            arcpy.SelectLayerByAttribute_management(display_lyr, "ADD_TO_SELECTION", "OBJECTID = 5") # this is to extend map west a bit 
        
        elif routesInclude=='lalb_exit' :
            route_select = ' ( ("PORT1" in (3,4) and "PORT2">100 ) or ("PORT2" in (3,4) and "PORT1">100 ) ) '
            arcpy.SelectLayerByAttribute_management(ports_lyr, "NEW_SELECTION", "PORT_ID = 3 OR PORT_ID = 7 OR PORT_ID = 101")
            arcpy.SelectLayerByAttribute_management(display_lyr, "ADD_TO_SELECTION", "OBJECTID = 8") # this is to extend map west a bit 
            
        elif routesInclude=='lalb_all' :
            # port-to-port LA/LB
            route_select = ' ( ("PORT1" in (3,4) and "PORT2"<=13 and not "PORT2" in (0) ) or ("PORT2" in (3,4) and "PORT1"<=13 and not "PORT1" in (0) )  and (INTERP_FLA=0)  ) '
            arcpy.SelectLayerByAttribute_management(ports_lyr, "NEW_SELECTION", "PORT_ID = 3 OR PORT_ID = 7 OR PORT_ID = 101")
            arcpy.SelectLayerByAttribute_management(display_lyr, "ADD_TO_SELECTION", "OBJECTID = 8") # this is to extend map west a bit 
            
        elif routesInclude=='lalb_long' :
            # port-to-port LA/LB
            route_select = ' ( ("PORT1" in (3,4) and "PORT2">13 and "PORT2"<50 and not "PORT2" in (0) ) or ("PORT2" in (3,4) and "PORT1">13 and "PORT1"<50 and not "PORT1" in (0) )  ) '
            arcpy.SelectLayerByAttribute_management(ports_lyr, "NEW_SELECTION", "PORT_ID = 3 OR PORT_ID = 7 OR PORT_ID = 101")
            arcpy.SelectLayerByAttribute_management(display_lyr, "ADD_TO_SELECTION", "OBJECTID = 8") # this is to extend map west a bit 
        
        elif routesInclude=='sf_exit' :
            route_select = ' ( ("PORT1" in (1) and "PORT2">100 ) or ("PORT2" in (1) and "PORT1">100 ) ) '
            arcpy.SelectLayerByAttribute_management(ports_lyr, "NEW_SELECTION", "PORT_ID = 1 OR PORT_ID = 7 OR PORT_ID = 101")
            arcpy.SelectLayerByAttribute_management(display_lyr, "ADD_TO_SELECTION", "OBJECTID = 5") # this is to extend map west a bit 
        
        elif routesInclude=='sf_all' :
            # port-to-port SF
            route_select = ' ( ("PORT1" in (1) and "PORT2"<=13 and not "PORT2" in (0,3,4) ) or ("PORT2" in (1) and "PORT1"<=13 and not "PORT1" in (0,3,4)) and (INTERP_FLA=0) )  '
            arcpy.SelectLayerByAttribute_management(ports_lyr, "NEW_SELECTION", "PORT_ID = 1 OR PORT_ID = 7 OR PORT_ID = 101")
            arcpy.SelectLayerByAttribute_management(display_lyr, "ADD_TO_SELECTION", "OBJECTID = 5") # this is to extend map west a bit 

        elif routesInclude=='sf_long' :
            # port-to-port SF
            route_select = ' ( ("PORT1" in (1) and "PORT2">13 and "PORT2"<50 and not "PORT2" in (0,3,4) ) or ("PORT2" in (1) and "PORT1">13 and "PORT1"<50 and not "PORT1" in (0,3,4)) )  '
            arcpy.SelectLayerByAttribute_management(ports_lyr, "NEW_SELECTION", "PORT_ID = 1 OR PORT_ID = 7 OR PORT_ID = 101")
            arcpy.SelectLayerByAttribute_management(display_lyr, "ADD_TO_SELECTION", "OBJECTID = 5") # this is to extend map west a bit 
            
        else :
            no_tracks
            
        ## Output file
        map_out = os.path.join(mapsout_dir , 'tracks_%s_%s' % (vesselInclude, routesInclude) + "_%s" )

        for tag in track_file_tags:
            print "printing: %s, %s, %s" %(tag,vesselInclude,routesInclude)
            
            # select time
            if tag=="preECA" :
                 date_select = '( "t_eca1"<0 )'
            elif tag== "CA_ECA2009" :
                date_select = '( "t_eca1">=0 and "t_eca2"<0 )'
            elif tag== "CA_ECA2011" :
                 date_select = '( "t_eca2">=0 and "t_eca3"<0 )'
            elif tag== "CA_NA_2012" :
                date_select = '( "t_eca3">=0 and "t_eca5"<0 )'
            elif tag== "CANA01" :
                date_select = '("t_eca5">0 )'
            else : 
                no_tag
            
            # get tracks layer
            tracklayer = arcpy.mapping.Layer( track_file )
            tracklayer.name = "tracks"


            # print route_select + " and " + toInclude + " and " + date_select + "and" + tracks_cond

            # select tracks
            #tracklayer.definitionQuery = '(port1=1 and port2=6) or (port2=1 and port1=6)' + toInclude
            tracklayer.definitionQuery = route_select + " and " + toInclude + " and " + date_select + "and" + tracks_cond
            #print route_select + toInclude

            # update symbology to template
            arcpy.ApplySymbologyFromLayer_management(tracklayer,symLayer)
            #arcpy.mapping.UpdateLayer(df,tracklayer,sourceLayer, symbology_only = True)

            # add layer
            arcpy.mapping.AddLayer(df,tracklayer,"BOTTOM")

            # hide all eca layers and port layer
            ports_lyr.visible = False
            CAECA09_lyr.visible = False
            CAECA11_lyr.visible = False
            NAECA_lyr.visible = False
            display_lyr.visible = False
            study_area_lyr.visible = True 

            # add ECA boundaries here
            if tag=='CA_ECA2009' or tag=='preECA' :
                CAECA09_lyr.visible = True 

            if tag=='CA_ECA2011' or tag=='CA_NA_2012' :
                CAECA11_lyr.visible = True 

            if tag=='CA_NA_2012':
                NAECA_lyr.visible = True
                
            if tag=='CANA01':
                NAECA_lyr.visible = True

            # zoom to selected ports
            df.zoomToSelectedFeatures()
            #df.scale *= scale
                                    

            ## export
            #arcpy.mapping.ExportToPDF(mxd,map_out % (y,m) + '.pdf' ,"PAGE_LAYOUT",resolution=600)
            #arcpy.mapping.ExportToEPS(mxd,map_out % (tag) + '.eps'  ,"PAGE_LAYOUT",resolution=600)
            arcpy.mapping.ExportToPNG(mxd,map_out % (tag) + '.png'  ,"PAGE_LAYOUT",resolution=res)
            
            #arcpy.mapping.ExportToPDF(mxd,map_pdf % (y,m) ,df,df_export_width=1200,df_export_height=900)
            

            # removing track layer
            arcpy.mapping.RemoveLayer(df,arcpy.mapping.ListLayers(mxd, "tracks", df)[0])

            del tracklayer

        # after done with particular route, clear port selection
        arcpy.SelectLayerByAttribute_management(ports_lyr, "CLEAR_SELECTION")
        arcpy.SelectLayerByAttribute_management(display_lyr, "CLEAR_SELECTION")
            
except Exception as e:
    print(e)
    del tracklayer

# cleaning up
del ports_lyr
del mxd
del df
del symLayer
